global class addEmailstoCIH implements Messaging.InboundEmailHandler {
 
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
    Messaging.InboundEnvelope envelope) {
 
    Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
    
    //List<Task> tskList = new List<Task>();
    String myPlainText = '';

    // Add the email plain text into the local variable
    try
    {
          myPlainText = email.plainTextBody.substring(0, email.plainTextBody.indexOf('<stop>'));
    }
    catch (System.StringException e)
    {
         myPlainText = email.plainTextBody;
         System.debug('No <stop> in email: ' + e);
    }

    // new Task object to be created

    Task[] newTask = new Task[0];

    // Try to lookup any contacts based on the email from address
    // If there is more than 1 contact with the same email address
    // an exception will be thrown and the catch statement will be called
    try {
            
        system.debug('From Email Address: '+email.fromAddress); 
        
        if(!email.fromAddress.contains('@lodhagroup.com'))
        {
        
        List<List<SObject>> searchList  = [FIND :email.fromAddress IN EMAIL FIELDS 
                                    RETURNING Account
                                    (Id,OwnerId WHERE (Person_email_from_trigger__c =:email.fromAddress OR PersonEmail = :email.fromAddress OR CSS_Email_1__c = :email.fromAddress
                                                       OR CSS_Email_2__c = :email.fromAddress OR CSS_Email_3__c =:email.fromAddress))]; 

        Account [] accs = ((List<Account>)searchList[0]);
        
            // Add a new Task to the contact record we just found above
        if(accs.size() >0)
            {       
                for (Account accList:accs){
                    newTask.add(new Task(Description = myPlainText,
                    Priority = 'Normal',
                    Status = 'Inbound Email',
                    Subject = email.subject,
                    IsReminderSet = true,
                    ReminderDateTime = System.now()+1,
                    OwnerId = accList.OwnerId,  
                    whatid = accList.Id));
                }
            }else
            {
                User[] userRecs = [Select id from User WHERE email IN :email.toAddresses AND User.IsActive = True AND User.Profile.Name != 'Custom Overage High Volume Customer Portal'];
                
                for(User u:userRecs){
                    newTask.add(new Task(Description = myPlainText,
                    Priority = 'Normal',
                    Status = 'Inbound Email',
                    Subject = email.subject,
                    IsReminderSet = true,
                    ReminderDateTime = System.now()+1,
                    OwnerId = u.Id 
                    //whatid = accList.Id
                    ));
                }
            }
        }
        else
        {
            List<Account> completeAccList = new List<Account>();
            Account [] accs;
            List<List<SObject>> searchList = new List<List<SObject>>();
            for(Integer i = 0; i < email.toAddresses.size(); i++){
            
            searchList  = [FIND :email.toAddresses[i] IN EMAIL FIELDS 
                                RETURNING Account
                                (Id,OwnerId WHERE (Person_email_from_trigger__c =:email.toAddresses OR PersonEmail = :email.toAddresses OR CSS_Email_1__c = :email.toAddresses
                                                   OR CSS_Email_2__c = :email.toAddresses OR CSS_Email_3__c =:email.toAddresses))]; 
            
            //Account [] 
            accs = ((List<Account>)searchList[0]);
            completeAccList.addAll(accs);
            }
            system.debug('AccountList: '+ completeAccList );
            //accs = ((List<Account>)searchList[0]);
            
            // Add a new Task to the contact record we just found above
            if(accs.size() >0)
                {       
                    for (Account accList:completeAccList){
                        newTask.add(new Task(Description = myPlainText,
                        Priority = 'Normal',
                        Status = 'Inbound Email',
                        Subject = email.subject,
                        IsReminderSet = true,
                        ReminderDateTime = System.now()+1,
                        OwnerId = accList.OwnerId,  
                        whatid = accList.Id));
                    }
                }
        }
            insert newTask;
            for(Task t:newTask){
            if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) {
                for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) {
                    Attachment attachment = new Attachment();
                    // attach to the newly created contact record
                    //attachment.ParentId = accList.Id;
                    attachment.ParentId = t.id;
                    attachment.ownerid=t.ownerid;
                    attachment.Name = email.binaryAttachments[i].filename;
                    attachment.Body = email.binaryAttachments[i].body;
                    insert attachment;
                  }
            }else if(email.textAttachments != null && email.textAttachments.size() > 0){
                    for (Messaging.Inboundemail.TextAttachment tAttachment: email.textAttachments) {
                      Attachment attachment = new Attachment();
                     
                      attachment.Name = tAttachment.fileName;
                      attachment.Body = Blob.valueOf(tAttachment.body);
                      //attachment.ParentId = accList.Id;
                      attachment.ParentId = t.id;
                      insert attachment;
                    }
                }
            }
    }

    catch (System.QueryException e) {
       System.debug('Query Issue: ' + e);
    }

// Set the result to true, no need to send an email back to the user
// with an error message

    result.success = true; 
    return result;
 
  }
 
}